package com.anuode.entity;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.anuode.core.controll.AppContextControll;
import com.anuode.core.controll.KennerControll;
import com.anuode.entity.BaseActivity;
import com.anuode.entity.BaseActivityInterface;
import com.anuode.entity.Task;

/**
 * Created by xudong on 2015/4/4.
 * a task server ,what can used in UI thread , and will AUTO-REFRESH UI
 * Activity must Override freash method and  implements BaseActivityInterface.
 */
public class TaskBaseServer {
    protected static KennerControll controll;// a controll
    protected MyHandler myHandler;//handler
    private static HandlerThread handlerThread;//Thread to run looper , not Run on UI or Main Thread.
    protected BaseActivityInterface activity;
    protected String view = "PersonalActivity";
    protected static final String BASE_URL = "http://dev.m.wetrip.com/";
    public TaskBaseServer(BaseActivityInterface activity) {
        this.activity = activity;
        init();
    }

    /**
     * init this server
     */
    void init() {
        controll = controll == null ? (KennerControll) AppContextControll.app.cache.get("KennerControll") : controll;
        if (handlerThread == null) {
            handlerThread = new HandlerThread("service");
            handlerThread.start();
        }
        myHandler = new MyHandler(handlerThread.getLooper());
    }

    /**
     * If task has a handler (must use mHander)
     *
     * @param msg
     */
    public void callBack(Message msg) {
    }

    /**
     * runOnUiThread
     *
     * @param msg
     */
    protected void runOnUiThread(final Object msg) {
        //use activity to run on UI thread
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                activity.freash(msg);
            }
        });
    }

    /**
     * @param task
     */
    public void doTask(Task task) {
        if (task.handler == null)
            task.handler = myHandler;
        controll.doTask(task);
    }

    /**
     * a handler ,run on another thread(not run on ui thread).
     */
    public class MyHandler extends Handler {
        public MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Message msg1 = Message.obtain();
            msg1.what = msg.what;
            msg1.obj = msg.obj;
            callBack(msg1);
        }
    }

    /**
     * Free this HandlerThread
     */
    public static void free() {
        if (handlerThread != null)
            handlerThread.quit();
        handlerThread = null;
    }


    public void setView(String view) {
        this.view = view;
    }

    public String getView() {
        return view;
    }
}
